<template>
  <div class="productManager">
    <div class="breadcrumb">
      <el-icon>
        <Location />
      </el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>消息管理</el-breadcrumb-item>
        <el-breadcrumb-item>消息列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="公告管理" name="first">
        <div class="content">
          <div class="top">
            <div style="display:flex;">
              <el-input
                v-model="message_title"
                style="width: 200px"
                placeholder="请输入主题进行搜索"
                :prefix-icon="Search"
              ></el-input>
              <el-button type="primary" @click="togetAnnouncementManagement()">确认</el-button>

              <el-radio-group
                style="margin-left:30px;"
                v-model="message_level"
                @change="togetAnnouncementManagement"
              >
                <el-radio label>全部</el-radio>
                <el-radio label="一般">一般</el-radio>
                <el-radio label="重要">重要</el-radio>
                <el-radio label="必要">必要</el-radio>
              </el-radio-group>
            </div>
            <div>
              <!-- <el-button>全部公告</el-button> -->
              <el-button type="primary" @click="dialogVisible = true; isEdit = false;">发布公告</el-button>
            </div>
          </div>

          <el-table :data="tableData" border style="width: 100%">
            <el-table-column show-overflow-tooltip type="index" width="50" />
            <el-table-column show-overflow-tooltip prop="message_title" label="公告主题" />
            <el-table-column show-overflow-tooltip prop="message_category" label="类型" />
            <el-table-column show-overflow-tooltip prop="message_publish_deparment" label="发布部门" />
            <el-table-column show-overflow-tooltip prop="message_publish_name" label="发布人" />
            <el-table-column show-overflow-tooltip prop="message_receipt_object" label="接收对象" />
            <el-table-column show-overflow-tooltip prop="message_level" label="公告等级">
              <template #default="scope">
                <el-tag :type="tagType(scope.row)">{{scope.row.message_level}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="message_create_time" label="发布时间" />
            <el-table-column show-overflow-tooltip prop="message_update_time" label="最新编辑时间" />
            <el-table-column
              show-overflow-tooltip
              prop="message_click_number"
              label="阅读次数"
              width="200px"
            />
            <el-table-column
              show-overflow-tooltip
              prop="message_content"
              label="内容"
              min-width="200px"
            >
              <template #default="scope">
                <div v-html="scope.row.message_content"></div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="150">
              <template #default="scope">
                <el-button
                  size="small"
                  type="success"
                  @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pageNum"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="系统消息" name="second">
        <div class="content">
          <div class="top1">
            <div style="display:flex;">
              <el-button
                type="primary"
                @click="systemDialogVisible = true; isSystemEdit = false;"
              >发布系统消息</el-button>
            </div>
          </div>

          <el-table :data="tableDataExamine" border style="width: 100%">
            <el-table-column show-overflow-tooltip type="index" width="50" />
            <el-table-column show-overflow-tooltip prop="message_title" label="消息主题" />
            <el-table-column show-overflow-tooltip prop="message_publish_name" label="发布者" />
            <el-table-column show-overflow-tooltip prop="message_click_number" label="阅读人数" />
            <el-table-column show-overflow-tooltip prop="message_create_time" label="发布时间" />
            <el-table-column
              show-overflow-tooltip
              prop="message_content"
              label="内容"
              min-width="200px"
            >
              <template #default="scope">
                <div v-html="scope.row.message_content"></div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="150">
              <template #default="scope">
                <el-button
                  size="small"
                  type="success"
                  @click="handleEdit1(scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete1(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pageNum1"
            :page-size="pageSize1"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      draggable
      v-model="dialogVisible"
      :title="(isEdit ? '修改' : '新建') + '公司公告'"
      width="30%"
      @close="dialogVisibleClose(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="主题" prop="message_title">
          <el-input v-model="ruleForm.message_title" placeholder="主题" />
        </el-form-item>
        <el-form-item label="发布部门" prop="message_publish_deparment">
          <el-select
            v-model="ruleForm.message_publish_deparment"
            placeholder="发布部门"
            style="width:100%"
          >
            <el-option
              :label="item.name"
              :value="item.name"
              v-for="item in departmentList"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布人" prop="message_publish_name">
          <el-input v-model="ruleForm.message_publish_name" placeholder="发布人" disabled />
        </el-form-item>
        <!-- <el-form-item label="消息类型" prop="message_category">
          <el-select v-model="ruleForm.message_category" placeholder="消息类型" style="width:100%">
            <el-option label="公告管理" value="公告管理" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="接收部门" prop="message_receipt_object">
          <el-select
            v-model="ruleForm.message_receipt_object"
            placeholder="接收部门"
            style="width:100%"
          >
            <el-option
              :label="item.name"
              :value="item.name"
              v-for="item in departmentList"
              :key="item.id"
            />

            <el-option label="全体成员" value="全体成员" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告等级" prop="message_level">
          <el-select v-model="ruleForm.message_level" placeholder="公告等级" style="width:100%">
            <el-option label="一般" value="一般" />
            <el-option label="重要" value="重要" />
            <el-option label="必要" value="必要" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="message_content">
          <div style="border: 1px solid #ccc;width:100%;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef1"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px;width:100%;"
              v-model="ruleForm.message_content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated1"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      draggable
      v-model="systemDialogVisible"
      :title="(isSystemEdit ? '修改' : '新建') + '系统消息'"
      width="30%"
      @close="dialogVisibleClose(systemruleFormRef)"
    >
      <el-form
        ref="systemruleFormRef"
        :model="systemruleForm"
        :rules="systemrules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="主题" prop="message_title">
          <el-input v-model="systemruleForm.message_title" placeholder="主题" />
        </el-form-item>
        <el-form-item label="发布人" prop="message_publish_name">
          <el-input v-model="systemruleForm.message_publish_name" placeholder="发布人" disabled />
        </el-form-item>

        <el-form-item label="消息类型" prop="message_category">
          <el-select
            v-model="systemruleForm.message_category"
            placeholder="消息类型"
            style="width:100%"
          >
            <el-option label="公告管理" value="公告管理" disabled />
            <el-option label="系统消息" value="系统消息" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="message_content">
          <div style="border: 1px solid #ccc;width:100%;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px;width:100%;"
              v-model="systemruleForm.message_content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="systemDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm1(systemruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, toRefs, shallowRef, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import {
  getAnnouncementManagement, //获取公告管理
  addAnnouncementManagement, // 新增公告管理
  firstDeleteAnnouncementManagement,
  editAnnouncementManagement,
  getSystemMessages, // 获取系统消息
  editSystemMessages,
  addReadList,
  editReadList
} from "@/api/message";
import { getDepartment } from "@/api/user";
import { addOperationLog } from "@/api/log";

import { useRouter } from "vue-router";
const router = useRouter();

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notebook,
  UserFilled,
  User,
  Notification,
  ChatRound
} from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// mode
const mode = ref("default");
// 内容 HTML
// const valueHtml = ref();
const toolbarConfig = {
  excludeKeys: []
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      //上传图片配置
      server: "http://127.0.0.1:3007/set/uploadCompanyPicture", //上传接口地址
      fieldName: "file", //上传文件名
      methods: "post",
      metaWithUrl: true, // 参数拼接到 url 上
      // 单个文件上传成功之后
      // onSuccess(file, res) {
      // },
      // 自定义插入图片
      customInsert(res, insertFn) {
        insertFn(res.url);
      }
    }
  }
};
// 上传图片，修改 uploadImage 菜单配置
// 需要注意的是，如何去修改参数？
toolbarConfig.excludeKeys = [
  "blockquote",
  "bgColor",
  "color",
  "group-more-style",
  "fontFamily",
  "bulletedList",
  "numberedList",
  "lineHeight",
  "todo",
  "emotion",
  "insertLink",
  "group-video",
  "insertTable",
  "codeBlock",
  "divider",
  "fullScreen"
  // 'group-image',

  // 排除菜单组，写菜单组 key 的值即可
];

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const activeName = ref("first");
const message_level = ref("");
const dialogVisible = ref(false);
const isEdit = ref(false);
const tableData = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const handleSizeChange = val => {
  pageSize.value = val;
  togetAnnouncementManagement();
};
const handleCurrentChange = val => {
  pageNum.value = val;
  togetAnnouncementManagement();
};
const dialogVisibleClose = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};

const ruleFormRef = ref();
const ruleForm = reactive({
  id: "",
  message_title: "",
  message_publish_deparment: "",
  message_publish_name: localStorage.getItem("name"),
  message_category: "公告管理",
  message_receipt_object: "",
  message_level: "",
  message_content: ""
});
const rules = reactive({
  message_title: [{ required: true, message: "主题", trigger: "blur" }],
  message_publish_deparment: [
    { required: true, message: "发布部门", trigger: "blur" }
  ],
  message_publish_name: [
    { required: true, message: "发布人", trigger: "blur" }
  ],
  // message_category: [{ required: true, message: "消息类型", trigger: "blur" }],
  message_receipt_object: [
    { required: true, message: "接收部门", trigger: "blur" }
  ],
  message_level: [{ required: true, message: "公告等级", trigger: "blur" }],
  message_content: [{ required: true, message: "内容", trigger: "blur" }]
});
const rowInfo = ref();
const handleEdit = (index, row) => {
  rowInfo.value = row;
  isEdit.value = true;
  ruleForm.id = row.id;
  ruleForm.message_title = row.message_title;
  ruleForm.message_publish_deparment = row.message_publish_deparment;
  ruleForm.message_publish_name = row.message_publish_name;
  ruleForm.message_receipt_object = row.message_receipt_object;
  ruleForm.message_level = row.message_level;
  ruleForm.message_content = row.message_content;
  dialogVisible.value = true;
};
const handleDelete = (index, row) => {
  ElMessageBox.confirm("是否删除此公告？", "删除操作", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let query = {
        id: row.id
      };
      firstDeleteAnnouncementManagement(query).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({
          operation_person: localStorage.getItem("name"),
          operation_content: "对id是" + row.id + "的公告删除",
          operation_level: "高级"
        });

        togetAnnouncementManagement();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

const pageNum1 = ref(1);
const pageSize1 = ref(10);
const handleSizeChange1 = val => {
  pageSize.value = val;
  togetSystemMessages();
};
const handleCurrentChange1 = val => {
  pageNum.value = val;
  togetSystemMessages();
};

const handleEdit1 = (index, row) => {
  isSystemEdit.value = true;
  systemruleForm.id = row.id;
  systemruleForm.message_title = row.message_title;
  systemruleForm.message_publish_name = localStorage.getItem("name");
  systemruleForm.message_category = "系统消息";
  systemruleForm.message_content = row.message_content;
  systemDialogVisible.value = true;
};
const handleDelete1 = (index, row) => {
  ElMessageBox.confirm("是否删除此系统消息？", "删除操作", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let query = {
        id: row.id
      };
      firstDeleteAnnouncementManagement(query).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({
          operation_person: localStorage.getItem("name"),
          operation_content: "对id是" + row.id + "的系统消息删除",
          operation_level: "高级"
        });

        togetSystemMessages();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};
const message_title = ref("");
const togetAnnouncementManagement = () => {
  let data = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    message_title: message_title.value,
    message_level: message_level.value
  };
  getAnnouncementManagement(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  });
};

const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        let data = {
          id: ruleForm.id,
          message_title: ruleForm.message_title,
          message_publish_deparment: ruleForm.message_publish_deparment,
          message_category: ruleForm.message_category,
          message_receipt_object: ruleForm.message_receipt_object,
          message_level: ruleForm.message_level,
          message_content: ruleForm.message_content
        };
        // console.log({
        //     id: ruleForm.id,
        //     department: ruleForm.message_receipt_object,
        //     oldDepartment:  rowInfo.value.message_receipt_object
        //   });
        //   return
        editAnnouncementManagement(data).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "对id是" + ruleForm.id + "的公告修改",
            operation_level: "一般"
          });

          let res1 = await editReadList({
            id: ruleForm.id,
            department:  ruleForm.message_receipt_object,
            oldDepartment:  rowInfo.value.message_receipt_object
          });
          store.commit("setReadList",JSON.parse(res1.data.data));  
          togetAnnouncementManagement();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      } else {
        addAnnouncementManagement(ruleForm).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "发布公告",
            operation_level: "高级"
          });
          let res1 = await addReadList({
            id: res.data.data.id,
            department: res.data.data.department
          });
          store.commit("setReadList",JSON.parse(res1.data.data)); 
          togetAnnouncementManagement();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const editorRef1 = ref();
const handleCreated1 = editor => {
  editorRef1.value = editor; // 记录 editor 实例，重要！
};
const systemruleFormRef = ref();
const systemruleForm = reactive({
  id: "",
  message_title: "",
  message_publish_name: localStorage.getItem("name"),
  message_category: "系统消息",
  message_content: ""
});
const systemrules = reactive({
  message_title: [{ required: true, message: "主题", trigger: "blur" }],
  message_publish_name: [
    { required: true, message: "发布人", trigger: "blur" }
  ],
  message_category: [{ required: true, message: "消息类型", trigger: "blur" }],
  message_content: [{ required: true, message: "内容", trigger: "blur" }]
});
const total1 = ref(0);
const tableDataExamine = ref([0]);
const isSystemEdit = ref(true);
const systemDialogVisible = ref(false);
const togetSystemMessages = () => {
  let data = {
    pageNum: pageNum1.value,
    pageSize: pageSize1.value
  };
  getSystemMessages(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    tableDataExamine.value = res.data.data.list;
    total1.value = res.data.data.total;
  });
};

const submitForm1 = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isSystemEdit.value) {
        let data = {
          id: systemruleForm.id,
          message_title: systemruleForm.message_title,
          message_content: systemruleForm.message_content
        };
        editSystemMessages(data).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "对id是" + ruleForm.id + "的系统消息修改",
            operation_level: "一般"
          });

          togetSystemMessages();
          ElMessage.success(res.data.message);
          systemDialogVisible.value = false;
        });
      } else {
        addAnnouncementManagement(systemruleForm).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "发布系统消息",
            operation_level: "高级"
          });

          togetSystemMessages();
          ElMessage.success(res.data.message);
          systemDialogVisible.value = false;
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const tagType = row => {
  if (row.message_level == "必要") {
    return "danger";
  } else if (row.message_level == "重要") {
    return "warning";
  } else {
    return "";
  }
};

const departmentList = ref([]);
const togetDepartment = () => {
  getDepartment().then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    departmentList.value = res.data.data;
  });
};
//声明周期函数，自动执行初始化
onMounted(() => {
  togetAnnouncementManagement();
  togetSystemMessages();
  togetDepartment();
});
</script>

<style scoped lang="scss">
.productManager {
}
.breadcrumb {
  display: flex;
  margin-bottom: 10px;
}
.content {
  background: #fff;
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .top1 {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
}
</style>